/*
 * With gdbus
 */
#include <stdio.h>
#include <stdlib.h>
#include <gio/gio.h>
#include "common.h"

#define OFONO_MESSAGE_MANAGER "org.ofono.MessageManager"

static GMainLoop *main_loop;

static void on_response_callback(GObject *source_object, GAsyncResult *result, gpointer user_data) {
    GError *error = NULL;
    GDBusConnection *conn = NULL;
    GVariant *dbus_result = NULL;
    int data = 0;
    conn = G_DBUS_CONNECTION(source_object);
    dbus_result = g_dbus_connection_call_finish(conn, result, &error);
    if (dbus_result == NULL) {
        printf("error on_response_callback: %s", error->message);
        g_error_free(error);
        return;
    }
    const char *path = NULL;
    g_variant_get(dbus_result, "(o)", &path);
    printf("return is '%s'\n", path);
    g_main_loop_quit(main_loop);
}

int main(int argc, char **argv) {
    const char *dst_1 = "10087";
    const char *msg_1 = "the quick brown fox jumps over the lazy dog.";
    gpointer callback_data;
    g_type_init();
    GDBusConnection *conn = get_system_bus_connection();
    const gchar *modems[MODEM_COUNT_LIMIT];
    gsize modem_count = 0;
    get_modem_paths(modems, &modem_count);
    if (modem_count < 1) {
        g_print("no modems ready, return\n");
        return -1;
    }
    GError *error = NULL;
    GVariant *result = g_dbus_connection_call_sync(conn, OFONO_SERVICE_NAME, modems[0],
            OFONO_MESSAGE_MANAGER, "SendMessage", g_variant_new("(ss)", dst_1, msg_1),
            G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
    if (result == NULL) {
        printf("error: %s\n", error->message);
        return -1;
    }
    const gchar *path;
    g_variant_get(result, "(o)", &path);
    printf("path is %s\n", path);
    
    /* use asynchronous call, which you must finish the call in specified callback */
    g_print("now let's try asynchronous call\n");
    const char *dst_2 = "1028384";
    const char *msg_2 = "freedom is nothing but a chance to be better";
    main_loop = g_main_loop_new(NULL, FALSE);
    g_dbus_connection_call(conn, OFONO_SERVICE_NAME, OFONO_MODEM_PATH, OFONO_MESSAGE_MANAGER,
            "SendMessage", g_variant_new("(ss)", dst_2, msg_2), G_VARIANT_TYPE("(o)"),
            G_DBUS_CALL_FLAGS_NONE, -1, NULL,
            (GAsyncReadyCallback) on_response_callback, callback_data);
    g_main_loop_run(main_loop);
    for (int i = 0; i < modem_count; i++) {
        g_free(modems[i]);
    }
    return 0;
}
